<?php
class ModelService
{
	private $modelName;
	private $tableName;
	private $fieldNames;
	private $fieldTypes;
	private $displayNames;

	/**
	 * 新增模版数据
	 * @Author   Leikes
	 * @DateTime 2016-01-12T16:39:50+0800
	 */
	public function addModel()
	{
		try
		{
			$model=new Model;
			$model->model_name=$this->modelName;
			$model->table_name=$this->tableName;
			$model->save();
			$modelOne=Model::where('table_name','=',$this->tableName)->first();
			$modelId=modelOne->id;
			for($i=0;$i<count($this->fieldNames);$i++)
			{
				$field               =new Field;
				$field->model_id     =$modelId;
				$field->field_name   =$this->fieldNames[$i];
				$field->field_type   =$this->fieldTypes[$i];
				$field->display_name =$this->displayNames[$i];
				$field->save();
			}
			$this->createTable();
			$this->createModel();
		}
		catch(Exception $e)
		{
			return CMSException::$addModelErr;
		}

		return CMSException::$ok;
	}

	/**
	 * 新增模版数据同时新增表格
	 * @Author   Leikes
	 * @DateTime 2016-01-12T16:56:57+0800
	 */
	public function createTable()
	{
		Schema::create($this->tableName.'s',function($table)
		{
			$table->increments('id');
			for($i=0;$i<count($this->fieldNames);$i++)
			{
				$fieldType=$fieldTypes[$i];
				$table->$fieldType($this->fieldNames[$i]);
			}
			$table->timestamps();
		});
	}

	/**
	 * 创建框架model文件
	 * @Author   Leikes
	 * @DateTime 2016-01-12T17:08:48+0800
	 */
	public function createModel()
	{
		File::put('../app/models/'.$this->tableName.'.php','<?php'."\n".'class '.$this->tableName."\n".'{	protected $table='.$this->tableName.'s;	}');
	}

	public function deleteModel($modelId)
	{	
		$fields =Field::where('model_id','=',$modelId)->get();
		$model  =Model::find($modelId);

		File::delete('../app/models/'.$model->model_name.'.php');
		$fields->delete();
		$model->delete();
		Schema::drop($model->table_name);

	}

	public function setModelName($modelName)
	{
		$this->modelName    =$modelName;
	}
	
	public function setTableName($tableName)
	{
		$this->tableName    =$tableName;
	}
	
	public function setFieldNames($fieldNames)
	{
		$this->fieldNames   =$fieldNames;
	}
	
	public function setFieldTypes($fieldTypes)
	{
		$this->fieldTypes   =$fieldTypes;
	}
	
	public function setDisplayNames($displayNames)
	{
		$this->displayNames =$displayNames;
	}
}
?>